# coding:utf-8
import argparse
import os
from decimal import Decimal
import numpy as np
from scipy import signal

import config as conf


def uploadedData(filename, csvbool=True):
    if csvbool:
        csvlist = list()
        with open(filename, 'r') as csvfile:
            for e in csvfile:
                if len(e.split()) == 1:
                    csvlist.append(float(e))
                else:
                    csvlist.append(e)
    return csvlist


def model_predict(file_path):
    data = uploadedData(file_path, csvbool=True)
    data = data[1:]
    size = len(data)
    if size > 9001:
        size = 9001
        data = data[:size]
    config = conf.get_config()
    #
    data, peaks = preprocess(data, config)
    return predictByPart(data, peaks)

def model_predict_data(data):
    data = data[1:]
    size = len(data)
    if size > 9001:
        size = 9001
        data = data[:size]
    config = conf.get_config()
    #
    data, peaks = preprocess(data, config)
    return predictByPart(data, peaks)

def get_config():
    parser = argparse.ArgumentParser()
    config, unparsed = parser.parse_known_args()
    return config


def preprocess(data, config):
    sr = config.sample_rate
    if sr is None:
        sr = 300
    data = np.nan_to_num(data)  # removing NaNs and Infs

    data = signal.resample(data, int(len(data) * 360 / sr))  # resample to match the data sampling rate 360(mit), 300(cinc)
    from sklearn import preprocessing
    data = preprocessing.scale(data)
    from scipy.signal import find_peaks
    peaks, _ = find_peaks(data, distance=150)
    data = data.reshape(1, len(data))
    data = np.expand_dims(data, axis=2)  # required by Keras
    return data, peaks


def predictByPart(data, peaks):
    classesM = ['正常心跳', '室性早搏', '有节奏的搏动', '房性早搏', '心室搏动与正常搏动的融合', '噪声']  # ,'L','R','f','j','E','a','J','Q','e','S']
    predicted = list()
    result = ""
    counter = [0] * len(classesM)

    model = load_model('models/MLII-latest.hdf5')
    config = get_config()
    last_end = 0
    for i, peak in enumerate(peaks[3:-1]):
        total_n = len(peaks)
        start, end = peak - config.input_size // 2, peak + config.input_size // 2
        start_s = start / 360
        start_s = Decimal(start_s).quantize(Decimal('0.0000'))
        end_s = end / 360
        end_s = Decimal(end_s).quantize(Decimal('0.0000'))
        prob = model.predict(data[:, start:end])
        prob = prob[:, 0]
        ann = np.argmax(prob)
        counter[ann] += 1
        last_start = start_s

        pr1 = Decimal(100 * prob[0, ann]).quantize(Decimal('0.00'))

        if classesM[ann] != "N":
            print("The {}/{}-record classified as {} with {:3.1f}% certainty".format(i, total_n, classesM[ann],
                                                                                     100 * prob[0, ann]))
        if (classesM[ann] != "正常心跳") & (last_start >= last_end):
            # result += "['" + classesM[ann] + "'"+"," +"["+ str(start_s) + "," + str(end_s) + "]],"
            result += "{'arrCoordinate':[" + str(start_s) + "," + str(end_s) + "],'begin':" + str(
                start) + ",'end':" + str(end) + ",'ecgType':'" + \
                      classesM[ann] + str(pr1) + "%','sid':1},"
        last_end = end_s
        result_json = result
        predicted.append([classesM[ann], prob])
        if classesM[ann] != 'N' and prob[0, ann] > 0.95:
            import matplotlib.pyplot as plt
            plt.plot(data[:, start:end][0, :, 0], )
            # 存储处理结果
            mkdir_recursive('results')
            plt.savefig('results/hazard-' + classesM[ann] + '.png', format="png", dpi=300)
            plt.close()
    result += "{}-N, {}-V, {}-Paced, {}-A, {}-F, {}-Noise".format(counter[0], counter[1], counter[2],
                                                                  counter[3], counter[4], counter[5])

    # save_dict(os.path.join("json", sample + '.json'), result_json)

    return predicted, result, result_json


def mkdir_recursive(path):
    if path == "":
        return
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        mkdir_recursive(sub_path)
    if not os.path.exists(path):
        print("Creating directory " + path)
        os.mkdir(path)

if __name__ == '__main__':
   data = sys.arg[1]
   result = model_predict_data(data)
   return result
